package com.lgc.demo.example.calculatenumberofpeople;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NumberOfPeople {
    private static int number;
    private static List<PeopleSetting> peopleSettingList;

    public void Init() throws ParseException {
        peopleSettingList = new ArrayList<>();
        PeopleSetting obj = new PeopleSetting();
        obj.setId(1);
        obj.setBeginNumber(1);
        obj.setEndNumber(100);
        obj.setBeginTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-04-30 18:00:00"));
        obj.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-04-30 19:00:00"));
        peopleSettingList.add(obj);

        PeopleSetting obj2 = new PeopleSetting();
        obj2.setId(1);
        obj2.setBeginNumber(101);
        obj2.setEndNumber(500);
        obj2.setBeginTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-04-30 19:00:00"));
        obj2.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-04-30 21:00:00"));
        peopleSettingList.add(obj2);

        PeopleSetting obj3 = new PeopleSetting();
        obj3.setId(1);
        obj3.setBeginNumber(501);
        obj3.setEndNumber(2000);
        obj3.setBeginTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-04-30 21:00:00"));
        obj3.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-05-01 08:00:00"));
        peopleSettingList.add(obj3);
    }

    public int getNumber(Date queryTime) throws ParseException {
        PeopleSetting currentSetting = getCurrentSetting(queryTime);
        if (currentSetting == null) {
            return number;
        } else {
            int calculateNumber = calculateResult(currentSetting, queryTime);

            if (calculateNumber < number) {
                return number;
            } else {
                number = calculateNumber;
                return calculateNumber;
            }
        }
    }

    private PeopleSetting getCurrentSetting(Date queryTime) throws ParseException {
        if (peopleSettingList == null) {
            Init();
        }

        PeopleSetting result = null;
        for (PeopleSetting item :
                peopleSettingList) {
            if (item.getBeginTime().compareTo(queryTime) <= 0 && item.getEndTime().compareTo(queryTime) >= 0) {
                result = item;
                break;
            }
        }

        return result;
    }

    private int calculateResult(PeopleSetting setting, Date queryTime) {
        long allDifference = setting.getEndTime().getTime() - setting.getBeginTime().getTime();
        long currentDifference = queryTime.getTime() - setting.getBeginTime().getTime();

        long addNumber = (setting.getEndNumber() - setting.getBeginNumber()) * currentDifference / allDifference;

        return setting.getBeginNumber() + (int) addNumber;
    }
}
